package projetstackoverflow

import org.springframework.dao.DataIntegrityViolationException

class QuestionController {

    static allowedMethods = [save: "POST", update: "POST", delete: "GET"]
	def beforeInterceptor = [action:this.&checkUser,except:['index','list','show']]
	
	def checkUser() {
		if(!session.author)
		{
			redirect(controller:'author',action:'login', params:['lastUri': (request.forwardURI - request.contextPath)])
			return false
		}
	}
	
    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = 4//Math.min(max ?: 10, 100)
		params.sort = params.sort ?: "date"
		params.order = params.order ?: "desc"
		def questionInstanceList =  Question.list(params)
		def total
		if(params.idTag)
		{
			def tag = Tag.get(params.idTag)
			if(tag)
			{
				questionInstanceList = Question.findAll("from Question as q where ? in elements(tags)", [tag])
				total =  questionInstanceList.size()
				questionInstanceList = Question.findAll("from Question as q where ? in elements(tags) order by date desc", [tag], params)
			}
		}
		else if(params.idAuthor)
		{
			def author = Author.get(params.idAuthor)
			if(author)
			{
				def offset = 0
				if(params.offset)
					offset = Integer.valueOf(params.offset)
				questionInstanceList = Question.findAll("from Question as q where author.id = "+params.idAuthor)
				total =  questionInstanceList.size()
				questionInstanceList = Question.findAll("from Question as q where author.id = "+params.idAuthor+" order by date desc", [ max: params.max, offset:offset])
			}
		}
		else
		{
			questionInstanceList = Question.list(params)
			total = Question.count()
		}
		
        [questionInstanceList:questionInstanceList, questionInstanceTotal: total]
    }

    def create() {
        [questionInstance: new Question(params)]
    }

    def save() {
		params.author = session.author

		
		if(params.tag != null)
		{
			def tagList = params.list("tag")
			params.tags = []
			for(def aTag : tagList)
			{
				def tag = Tag.findWhere(value:aTag)
				if(tag == null)
				{
					tag = new Tag(value:aTag, desc:'no desc')
					tag.save(flush: true)
				}
				params.tags.add(tag)
			}
		}
        def questionInstance = new Question(params)
		
		if(!questionInstance.date)
			questionInstance.date = new Date()
			
        if (!questionInstance.save(flush: true)) {
            render(view: "create", model: [questionInstance: questionInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'question.label', default: 'Question'), questionInstance.id])
        redirect(action: "show", id: questionInstance.id)
    }

    def show(Long id) {
        def questionInstance = Question.get(id)
        if (!questionInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'question.label', default: 'Question'), id])
            redirect(action: "list")
            return
        }
		
		
		def answersList
		if(params.sort == 'votes')
		{
			answersList = questionInstance.answers.sort{ it.countVotes() }.reverse()
		}
		else
		{
			answersList = questionInstance.answers.sort{ it.date }
		}
		
		
		questionInstance.viewsNumber++
		[answersList: answersList, questionInstance: questionInstance]
    }

    def edit(Long id) {
        def questionInstance = Question.get(id)
        if (!questionInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'question.label', default: 'Question'), id])
            redirect(action: "list")
            return
        }
		if(!(session.author.admin || session.author.id == questionInstance.author.id))
		{
			redirect(controller:'question', action:'show', id:id)
		}
        [questionInstance: questionInstance]
    }

    def update(Long id, Long version) {
        def questionInstance = Question.get(id)
        if (!questionInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'question.label', default: 'Question'), id])
            redirect(action: "list")
            return
        }
		
		if(session.author.admin || session.author.id == questionInstance.author.id)
		{
			if (version != null) {
				if (questionInstance.version > version) {
					questionInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
							  [message(code: 'question.label', default: 'Question')] as Object[],
							  "Another user has updated this Question while you were editing")
					render(view: "edit", model: [questionInstance: questionInstance])
					return
				}
			}
			if(session.author.admin) //L'admin peut tout modifier (titre, auteur...)
			{
				questionInstance.properties = params 
			}
			else //Le possesseur peut seulement modifier le contenu du message et les tags
			{
				questionInstance.content = params.content
				if(params.tag != null)
				{
					def tagList = params.list("tag")
					questionInstance.tags = []
					for(def aTag : tagList)
					{
						def tag = Tag.findWhere(value:aTag)
						if(tag == null)
						{
							tag = new Tag(value:aTag, desc:'no desc')
							tag.save(flush: true)
						}
						questionInstance.tags.add(tag)
					}
				}
			}
			questionInstance.editDate = new Date()
	
			if (!questionInstance.save(flush: true)) {
				render(view: "edit", model: [questionInstance: questionInstance])
				return
			}
	
			flash.message = message(code: 'default.updated.message', args: [message(code: 'question.label', default: 'Question'), questionInstance.id])
			redirect(action: "show", id: questionInstance.id)
		}
        
    }

    def delete(Long id) {
        def questionInstance = Question.get(id)
        if (!questionInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'question.label', default: 'Question'), id])
            redirect(action: "list")
            return
        }
		
        try {
			if(session.author.admin)
			{
				questionInstance.delete(flush: true)
				flash.message = message(code: 'default.deleted.message', args: [message(code: 'question.label', default: 'Question'), id])
				redirect(action: "list")
			}
			else
			{
				redirect(controller:'question', action:'show', id:id)
			}
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'question.label', default: 'Question'), id])
            redirect(action: "show", id: id)
        }
    }
}
